import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Administration of the database: connection, opening+closing, send queries.
 * @author Meiser Jonathan
 * @version 2011
 *
 */
public class Database
{
    protected Connection connect;
    private Statement state;  
    private ResultSet result;
    private String myDriver = null;
    private String myDB = null;
    private String myUser = null;
    private String myPasswd = null;
    
   
   /**
    * Constructor
    * @param driver
    * @param database
    * @param benutzer
    * @param password
    */
    public Database( String driver, String database, String user, String password )     																	
    {	
        if ( driver == null )
    		throw new RuntimeException("Driver is empty!");
    	if ( database == null )
    		throw new RuntimeException("Database is empty!");
    	if ( user == null )
    		throw new RuntimeException("User is empty!");
    	if ( password == null )
    		throw new RuntimeException("Password is empty!");
    	
    	this.myDriver  = driver;
    	this.myDB = database;
    	this.myUser = user;
    	this.myPasswd = password;
        		
        try 
        {
			Class.forName(this.myDriver);
		} 
        catch (ClassNotFoundException e) 
        {
			e.printStackTrace();
		}
       
    }
    

   /**
    * open connection
    */
    public void openDB()
    {
        try 
        {
			this.connect = DriverManager.getConnection(this.myDB, this.myUser, this.myPasswd);
			this.state   = connect.createStatement();
		} 
        catch (SQLException e) 
        {
			e.printStackTrace();
		}        
    }
    
    
    /**
     * Send query
     * @param query
     * @return ResultSet : line of the database
     */
    public ResultSet sendQuery(String query)
    {
        try
        {
            this.result = (ResultSet) state.executeQuery(query);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        return this.result;   
    }
    
    /**
     * Send update
     * @param query
     */
    public void sendUpdate(String query)
    {
        try
        {
            state.executeUpdate(query);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }   
    }

    
   /**
    * Close database
    */
    public void closeDB()
    {
      try 
      {
		 this.state.close();
		 this.connect.close();
      } 
      catch (SQLException e) 
      {
		e.printStackTrace();
      }    
    }   
}